<%@page import="org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException"%>
<%@page
	import="org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>
	<%
		//1、创建FileItemFactory对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//实例化对象，设置缓冲大小，设置临时目录(不写即为默认临时目录)
		factory.setSizeThreshold(2 * 1024 * 1024);
		factory.setRepository(new File("g:\\temp"));
		//2、创建ServletFileUpload对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		//设置文件名字符集，文件大小
		upload.setHeaderEncoding("UTF-8");
		//设置表单总大小
		upload.setSizeMax(50 * 1024);
		//设置单个文件大小上限
		upload.setFileSizeMax(50*1024);
		//判断是否为文件上传表单
		if (upload.isMultipartContent(request)) {
			try {
				//3、使用ServletFileUpload，将request转换成List
				List<FileItem> list = upload.parseRequest(request);
				//4、遍历集合
				for (int i = 0; i < list.size(); i++) {
					FileItem item = list.get(i);
					//4、1判断是否是文本
					if (item.isFormField()) {
						//取name和值
						out.print("name是" + item.getFieldName() + "<br/>");
						out.print("value是" + item.getString("UTF-8")
								+ "<br/>");
					} else {
						String fileName = item.getName();
						//.substring(item.getName().lastIndexOf(File.separator)+1);
						//判断文件类型，通过扩展名判断
						String suffix = fileName.substring(fileName
								.lastIndexOf(".") + 1);
						//判断文件类型，使用文件的内容类型进行判断
						List suffixes = Arrays.asList("gif", "txt", "jpg","png");
						if (suffixes.contains(suffix)) {
							//4.2是文件取文件名，保存文件
							out.print("文件名是" + item.getFieldName());
							out.print(fileName);

							item.write(new File("g:\\temp\\" + fileName));
						} else {
							out.print("该文件类型不允许上传");
						}

					}
				}
			} catch (SizeLimitExceededException e) {
				out.print("总文件大小超出上限，请压缩后再上传");
			}
			catch (FileSizeLimitExceededException e) {
				out.print("单文件大小超出上限，请压缩后再上传");
			}
			//普通表单
		} else {
			out.print("普通表单");
		}
	%>
</body>
</html>
